<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" offset="50">
        <ArticleItem :dataList="list" v-for="item in list" :key="item.art_id" :artObj="item" @dislike="dislikeFn"
          @report="reportFn"></ArticleItem>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem.vue'
import { Toast } from 'vant'
import { articlesListAPI, dislikeArticleAPI, reportArticleAPI } from '@/api/index.js'
export default {
  components: {
    ArticleItem
  },
  data() {
    return {
      // paramObj: {
      //   channel_id: this.cid,
      //   timestamp: new Date().getTime()
      // },
      // listData: [],
      list: [],
      loading: false, // 底部加载状态
      finished: false, // 数据是否全部加载完成
      nextTime: new Date().getTime(),
      isLoading: false// 顶部加载状态
    }
  },
  props: {
    cid: Number
  },
  methods: {
    async getList() {
      try {
        const { data: res } = await articlesListAPI({
          channelId: this.cid, // 默认推荐频道(id为0)
          timestamp: this.nextTime
        })
        console.log(res)
        // 数据已请求完，说明已到底部
        if (res.data.results.length === 0) {
          this.finished = true
        }
        // 将再次请求的数据与原数据进行合并
        this.list = [...this.list, ...res.data.results]
        // 将最新的时间戳赋值给theTime
        this.nextTime = res.data.pre_timestamp
        // 结束加载
        this.loading = false
      } catch (error) {
        return Promise.reject(new Error(error))
      }
    },
    // 底部加载事件
    // 网页打开list组件自动检查会触发一次onLoad, 所以我们要在有数据后再让onLoad里请求数据
    onLoad() {
      if (this.list.length > 0) {
        this.getList()
      }
    },
    // 顶部加载事件
    async onRefresh() {
      // this.list = []
      const { data: res } = await this.$http.get('/v1_0/articles', { params: { channel_id: this.cid, timestamp: this.nextTime } })
      this.list = res.data.results
      Toast('刷新成功')
      this.isLoading = false
    },
    // 不感兴趣
    async dislikeFn(id) {
      console.log(11)
      const res = await dislikeArticleAPI({
        artId: id
      })
      console.log(res)
      this.$msg({ type: 'success', message: '反馈成功' })
    },
    // 举报
    async reportFn(id, value) {
      const res = await reportArticleAPI({
        artId: id,
        artType: value
      })
      console.log(res)
      this.$msg({ type: 'success', message: '反馈成功' })
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style scoped lang = "less">

</style>
